<script lang='ts' setup>
import { reactive, ref } from 'vue' 
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadUserFile, UploadProps } from 'element-plus' 
import OSS from 'ali-oss';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ossConfig  } from '/@/api/common';
import { dirList, fileUpload } from '/@/api/commodity';
const emit = defineEmits(['refresh']);
const ruleForm = reactive({ 
	dirId:null,
	name: '',
	type: 1, 
})
const fileList = ref<UploadUserFile[]>([])
const state = reactive({
    dialog:{
        title:'',
        isShowDialog:false,
        loading:false,
    },
    treeData: [] as Array<any>,
    oss:{
        region: "oss-cn-beijing",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: "LTAI5t7TcfUri3FRXU7Gtx55",
        accessKeySecret: "Kc1KZ8A3MNd6fIQdS8etUhMDZHf3zE",
        // 填写Bucket名称。
        bucket: 'konli-klys',
    },
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<any>>({
	dirId: [{ required: true, message: '请选择上传分组', trigger: 'change' }], 
})


const getDirList = async() => {
    state.dialog.loading = true;
    const { results } = await dirList();
    state.treeData = results;
    state.dialog.loading = false;
}

const getOssConfig = async() => {
    state.dialog.loading = true;
    const { results } = await ossConfig();
    state.oss = results;
}

// 文件改变时回调钩子
const handleChange = (file, files) => {
    // file是当前上传的文件，files是当前所有的文件，
    fileList.value = files
}

const client = new OSS({
    region: state.oss.region,
    // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
    accessKeyId: state.oss.accessKeyId,
    accessKeySecret: state.oss.accessKeySecret,
    // 填写Bucket名称。
    bucket: state.oss.bucket,
});

const submitForm =  (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid, fields) => {
		if (valid) {
            const options = {
                meta: { temp: "konLi" },
                mime: "json",
                headers: { "Content-Type": "image/jpeg" },
            };
            const promises = fileList.value.map(file => {
                // 这里可以根据需要自定义上传的文件名和路径
                let fileName = Math.random().toString(36).slice(-5) + Date.now() + file.name;
                return client.put(fileName, file.raw, options);
            });
            console.log(fileList);
            // 等待所有上传任务完成
            Promise.all(promises).then(async (filelist:any)  => {
                const fileListx = filelist.map((item:any,index:number) => ({  
                    filename: item.name,
                    url: item.url,
                    filesize: fileList.value[index].size,
                    fileType:0,
                    extension: item.url.split('.').pop().toLowerCase(),
                }));
                const { method } = await fileUpload(fileListx, ruleForm.dirId);
                if(method == 'success'){
                    emit('refresh');
                    closeDialog()
                    return ElMessage({
                        type: 'success',
                        message: '上传成功',
                    })
                }
            }).catch(error => {
                console.error('Error uploading files:', error);
            });
		} else {
			console.log('error submit!', fields)
		}
	})
}

const openDialog =() => {
    // 获取可上传目录
    getDirList();
    getOssConfig();
    ruleForm.dirId = null;
    fileList.value = [];
    state.dialog.isShowDialog = true
    
}

const moveToHandle = (event: any) => {
    console.log(event);
}

const closeDialog = () => {
    state.dialog.isShowDialog = false
}

// 暴露变量
defineExpose({
	openDialog
});

</script>
<template>
    <section>
        <el-dialog  title="图片上传" v-model="state.dialog.isShowDialog"  center class="borderRadius10" width="790">
            <section>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"> 
                    <el-form-item label="选择分组：" prop="dirId">
                        <el-select v-model="ruleForm.dirId" placeholder="选择上传分组" class="width305" >
                            <el-option v-for="item in state.treeData" :key="item.group" :label="item.name" :value="item.group" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上传图片：">
                        <el-upload accept=".jpeg,.png,.gif,.jpg" drag
                            :file-list="fileList" :multiple="true" action="#" list-type="picture-card" 
                            :auto-upload="false"
                            :on-change="handleChange">
                            <el-icon><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <el-row justify="center" class="mt20">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </el-row>
            </section>
        </el-dialog>
    </section>
</template>

<style lang='scss' scoped>
// 隐藏expand 箭头
:deep(.el-upload-list__item), :deep(.el-upload){
	width:96px;
    height:96px
    
}
:deep(.el-upload-dragger){
    height: inherit;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: none
}
</style>